const api = {
  get: async (url) => {
    try {
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }
      return await response.json();
    } catch (error) {
      console.error('Fetch failed:', error);
      throw error;
    }
  }
};

document.addEventListener('DOMContentLoaded', async function () {
    loadQuestions();
    loadArticles();
    try {
        const knowledgeData = await api.get('/data/knowledge.json'); // 路径修正
        renderKnowledgeCards(knowledgeData);
    } catch (error) {
        console.error('Error loading knowledge data:', error);
    }
});

// 加载问答数据
async function loadQuestions() {
    try {
        const data = await api.get('/data/questions.json'); // 路径修正

        const questionsContainer = document.getElementById('questions');
        data.forEach(question => {
            const questionElement = document.createElement('div');
            questionElement.className = 'mb-4';
            questionElement.innerHTML = `
                <strong class="text-lg">${question.question}</strong>
                <p class="text-gray-700">${question.answer}</p>
            `;
            questionsContainer.appendChild(questionElement);
        });
    } catch (error) {
        console.error('Error fetching questions:', error);
    }
}

// 加载文章数据
async function loadArticles() {
    try {
        const data = await api.get('/data/articles.json'); // 路径修正
        const articlesContainer = document.getElementById('articles');
        data.forEach(article => {
            const articleElement = document.createElement('div');
            articleElement.className = 'mb-6';
            articleElement.innerHTML = `
                <h3 class="text-xl font-semibold mb-2">${article.title}</h3>
                <p class="text-gray-700">${article.content}</p>
            `;
            articlesContainer.appendChild(articleElement);
        });
    } catch (error) {
        console.error('Error fetching articles:', error);
    }
}

// 动态生成知识卡片
function renderKnowledgeCards(knowledgeCards) {
    const container = document.getElementById('knowledgeCardsContainer');
    if (!container) return;

    container.innerHTML = knowledgeCards.map(card => `
        <a href="${card.link}" class="border border-gray-200 rounded-lg overflow-hidden shadow-md hover:shadow-lg transition duration-300 block">
            <img src="${card.image}" alt="${card.title}" class="w-full h-48 object-cover">
            <div class="p-4">
                <h3 class="text-xl font-semibold text-gray-800 mb-2">${card.title}</h3>
                <p class="text-gray-700 text-sm mb-3">${card.description}</p>
                <span class="text-blue-600 hover:underline text-sm">
                    <i class="fas fa-arrow-right mr-1"></i> 了解更多
                </span>
            </div>
        </a>
    `).join('');
}
